<?php
namespace Post\Controller;

use Common\Controller\ApiController;
use Util\ModelUtils;
use Common\Model\ModelException;

class PostFavoriteController extends ApiController
{
    public function addFavorite()
    {
        $user = $this->user;
        $input = $this->request();
        $postId = $input['post_id'];
        $post = D('Post')->find($postId);
        if (empty($post)) $this->errorResponse(80004);
        $favorite = M('PostFavorite')->where(['user_id' => $user['id'], 'post_id' => $postId])->find();
        if ($favorite) $this->errorResponse(80008);
        M('PostFavorite')->add([
            'user_id' => $user['id'],
            'post_id' => $postId,
            'create_time' => time(),
        ]);
        $this->createdResponse();
    }

    public function removeFavorite($postId)
    {
        $user = $this->user;
        $input = $this->request();
        $favorite = M('PostFavorite')->where(['user_id' => $user['id'], 'post_id' => $postId])->find();
        if (empty($favorite)) $this->errorResponse(80009);
        M('PostFavorite')->where(['user_id' => $user['id'], 'post_id' => $postId])->delete();
        $this->modifySuccessResponse();
    }
}
